<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;;
use think\Db;
use think\Session;
class Dp extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function expert()
    {
        $experts = Db::name('sy_expert')->order('id','desc')->select();
        return $this->fetch('', [
            'experts' => $experts
        ]);
    }

    public function expert_add()
    {
        return $this->fetch();
    }

    public function save_expert()
{
    $name = input('name');
    $desc = input('desc');
    $img = input('img');

    if(!$name){
        return json(['code' => 0, 'msg' => '专家姓名必填']);
    }
    if(!$img){
        return json(['code' => 0, 'msg' => '图片必填']);
    }

    $data = [
        'name' => $name,
        'desc' => $desc,
        'img' => $img,
        'create_time' => time()
    ];
    $flag = Db::name('sy_expert')->insertGetId($data);

    if(!$flag){
        return json(['code' => 0, 'msg' => '操作失败']);
    }
    
    return json(['code' => 1, 'msg' => '操作成功']);


}
    
    public function edit_expert()
{
    $name = input('name');
    $desc = input('desc');
    $img = input('img');
    $id = input('id');
    if(!$name){
        return json(['code' => 0, 'msg' => '专家姓名必填']);
    }
    if(!$img){
        return json(['code' => 0, 'msg' => '图片必填']);
    }

    $data = [
        'name' => $name,
        'desc' => $desc,
        'img' => $img,
        'create_time' => time()
    ];
    // $flag = Db::name('sy_expert')->insertGetId($data);
    $data = [
        'name' => $name,
        'desc' => $desc,
        'img' => $img,
    ];
    $flag = Db::name('sy_expert')->where('id',$id)->update($data);

    if(!$flag){
        return json(['code' => 0, 'msg' => '操作失败']);
    }

    return json(['code' => 1, 'msg' => '操作成功']);
}
    

public function expert_delete()
{
    $id = input('id');
    Db::name('sy_expert')->where('id', $id)->delete();
    return json(['code' => 1, 'msg' => '操作成功']);
}
    public function expert_edit()
    {
        $id = input('id');
        $record = Db::name('sy_expert')->where('id',$id)->find();
        return $this->fetch('', [
            'record' => $record
        ]);
    }



public function review()
{
    $reviews = Db::name('sy_review')->order('id', 'desc')->select();
    return $this->fetch('', [
        'reviews' => $reviews
    ]);
}

// 添加页面
public function review_add()
{
       $experts = Db::name('sy_expert')->field('id, name')->select();

    foreach ($experts as &$expert) {
        $expert['initial'] = $this->getFirstChar($expert['name']); // 调用拼音首字母方法
    }

    // 按拼音首字母排序
    usort($experts, function ($a, $b) {
        return strcmp($a['initial'], $b['initial']);
    });
    
    return $this->fetch('', [
        'expert_list'   => $experts,
    ]);
}



public function review_edit()
{
    $id = input('id');
    $review = Db::name('sy_review')->where('id', $id)->find();

    // 替代 Null 合并运算符
    $review['expert_ids'] = explode(',', isset($review['expert_ids']) ? $review['expert_ids'] : '');

    $typeList = Db::name('dp_type')->where('level', 2)->select();
    $experts = Db::name('sy_expert')->field('id, name')->select();

    foreach ($experts as &$expert) {
        $expert['initial'] = $this->getFirstChar($expert['name']);
    }
    usort($experts, function ($a, $b) {
        return strcmp($a['initial'], $b['initial']);
    });

    return $this->fetch('', [
        'expert_list' => $experts, // 修正此处
        'review' => $review
    ]);
}

// 保存新回顾
public function save_review()
{
    $course_name = input('course_name');
    $expert_team = input('expert_team');
    $cover_img = input('cover_img');
    $video_url = input('video_url');
    $description = input('description');
    $expert_ids = request()->post('expert_ids/a', []);

    if (!$course_name || !$cover_img || !$video_url) {
        return json(['code' => 0, 'msg' => '课程名称、封面图片和视频地址为必填项']);
    }

    // 防止 expert_ids 为 null 报错
    if (!is_array($expert_ids)) {
        $expert_ids = [];
    }

    $expert_id_str = implode(',', $expert_ids);

    $data = [
        'course_name' => $course_name,
        'expert_team' => $expert_team,
        'cover_img' => $cover_img,
        'video_url' => $video_url,
        'description' => $description,
        'expert_ids' => $expert_id_str,
        'create_time' => time()
    ];

    $flag = Db::name('sy_review')->insertGetId($data);

    if (!$flag) {
        return json(['code' => 0, 'msg' => '保存失败']);
    }

    return json(['code' => 1, 'msg' => '保存成功']);
}

// 编辑回顾
public function edit_review()
{
    $id = input('id');
    $course_name = input('course_name');
    $expert_team = input('expert_team');
    $cover_img = input('cover_img');
    $video_url = input('video_url');
    $description = input('description');

    if (!$id || !$course_name || !$cover_img || !$video_url) {
        return json(['code' => 0, 'msg' => 'ID、课程名称、封面图片和视频地址为必填项']);
    }

    $data = [
        'course_name' => $course_name,
        'expert_team' => $expert_team,
        'cover_img' => $cover_img,
        'video_url' => $video_url,
        'description' => $description
    ];

    $flag = Db::name('sy_review')->where('id', $id)->update($data);

    if (!$flag) {
        return json(['code' => 0, 'msg' => '更新失败']);
    }

    return json(['code' => 1, 'msg' => '更新成功']);
}

    public function edit_type()
    {
        $name = input('name');
        $desc = input('desc');
        $id = input('id');
        $count = Db::name('dp_type')->where('id',$id)->count();
        if(!$count){
            return json(['code' => 0, 'msg' => '信息不存在']);
        }
        if(!$name){
            return json(['code' => 0, 'msg' => '分类名称必填']);
        }
        $pid = input('pid',0);
        $level = 1;
        if($pid){
            $tmpLevel = Db::name('dp_type')->where('id',$pid)->value('level');
            $level = $tmpLevel + 1;
        }
        $data = [
            'name' => $name,
            'desc' => $desc,
            'create_time' => time(),
            'pid' => $pid,
            'level' => $level,
            'img' => input('img')
        ];
        Db::name('dp_type')->where('id',$id)->update($data);

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function record()
    {
        $limit = input('limit', 10);
        $page = input('page', 1);
        $record = Db::name('dp_record')
            ->alias('r')
            ->join('bd_dp_type t', 'r.type = t.id', 'LEFT')
            ->field('r.*, t.name as type_name')
            ->order('r.id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        $recordList = [];
        foreach ($record as $k => $v) {
            $recordList[] = [
                'id' => $v['id'],
                'name' => $v['name'],
                'desc' => $v['desc'],
                'img' => $v['img'],
                'type_name' => $v['type_name'],
                'create_time' => date('Y-m-d H:i:s',$v['create_time']),
            ];
        }

        return $this->fetch('', [
            'record_list' => $recordList,
            'record' => $record
        ]);
    }

    public function record_add()
    {
        $typeList = Db::name('dp_type')->where('level',2)->select();
        return $this->fetch('',[
            'type_list' => $typeList
        ]);
    }

    public function upload()
    {
        $config = [
            'size' => 20971520000,
            'ext'  => 'jpg,jpeg,png,gif,mp3,mp4,avi,mov'
        ];
        // 获取表单上传文件
        $file = $this->request->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $info = $file->validate($config)->move($upload_path);

        return json(['code' => 1, 'msg' => '上传成功','data' => [
            'url' => '/uploads/'.$info->getSaveName()
        ]]);
    }

    public function save_record()
    {
        $name = input('name');
        $desc = input('desc');
        $type = input('type');
        $img = input('img');
        if(!$name){
            return json(['code' => 0, 'msg' => '名称必填']);
        }
        if(!$type){
            return json(['code' => 0, 'msg' => '分类必填']);
        }
        if(!$img){
            return json(['code' => 0, 'msg' => '图片必填']);
        }
        $data = [
            'name' => $name,
            'desc' => $desc,
            'type' => $type,
            'img' => $img,
            'create_time' => time(),
            'sort' => input('sort',0),
            'video' => input('video','')
        ];
        $flag =Db::name('dp_record')->insertGetId($data);

        if(!$flag){
            return json(['code' => 0, 'msg' => '操作失败']);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function record_delete()
    {
        $id = input('id');
        Db::name('dp_record')->where('id',$id)->delete();

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public function record_edit()
    {
        $id = input('id');
        $record = Db::name('dp_record')->where('id',$id)->find();
        $typeList = Db::name('dp_type')->where('level',2)->select();

        return $this->fetch('',[
            'type_list' => $typeList,
            'record' => $record
        ]);
    }

    public function edit_record()
    {
        $name = input('name');
        $desc = input('desc');
        $type = input('type');
        $img = input('img');
        $id = input('id');
        $count = Db::name('dp_record')->where('id',$id)->count();
        if(!$count){
            return json(['code' => 0, 'msg' => '信息不存在']);
        }
        if(!$name){
            return json(['code' => 0, 'msg' => '名称必填']);
        }
        if(!$type){
            return json(['code' => 0, 'msg' => '分类必填']);
        }
        if(!$img){
            return json(['code' => 0, 'msg' => '图片必填']);
        }
        $data = [
            'name' => $name,
            'desc' => $desc,
            'type' => $type,
            'img' => $img,
            'sort' => input('sort',0),
            'video' => input('video','')
        ];
        Db::name('dp_record')->where('id',$id)->update($data);

        return json(['code' => 1, 'msg' => '操作成功']);
    }

public function course_cancel($id)
{
    // 取消课程
    $affected = Db::name('sy_course')->where('id', $id)->update(['status' => 2]);

    if (!$affected) {
        return json(['code' => 0, 'msg' => '取消失败']);
    }

    // 查询已预约该课程的用户 ID 列表
    $userIds = Db::name('sy_course_booking')->where('course_id', $id)->column('user_id');

    if ($userIds) {
        // 查询用户手机号
        $phones = Db::name('sy_user')->whereIn('id', $userIds)->column('phone');

        // 查询课程信息
        $courseInfo = Db::name('sy_course')->where('id', $id)->find();
        // var_dump($phones);
        // return;
        // 遍历发送短信
        foreach ($phones as $phone) {
            $this->sendSms($phone, $courseInfo['course_time'], $courseInfo['name']);
        }
    }

    return json(['code' => 1, 'msg' => '已取消课程并通知用户']);
}

// 发送短信方法（可抽离为公共方法）
private function sendSms($phone, $date, $courseName)
{
    $accessKeyId = "LTAI5tDJx3FZ11yagMXS9GNm";
    $accessSecret = "7Rsz02wqXazLuR6uyaq3XrF7B1IBoy";

    $params = [
        "PhoneNumbers" => $phone,
        "SignName" => "亭湖妇幼",
        "TemplateCode" => "SMS_485355497",
        "TemplateParam" => json_encode([
            "date" => $date,
            "name" => $courseName,
            "phone" => "81662819"
        ], JSON_UNESCAPED_UNICODE),
        "RegionId" => "cn-hangzhou",
        "Action" => "SendSms",
        "Version" => "2017-05-25",
        "AccessKeyId" => $accessKeyId,
        "Format" => "JSON",
        "SignatureMethod" => "HMAC-SHA1",
        "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
        "SignatureVersion" => "1.0",
        "SignatureNonce" => uniqid(),
    ];

    // 签名
    ksort($params);
    $sortedQueryString = "";
    foreach ($params as $key => $value) {
        $sortedQueryString .= "&" . rawurlencode($key) . "=" . rawurlencode($value);
    }
    $stringToSign = "GET&%2F&" . rawurlencode(substr($sortedQueryString, 1));
    $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessSecret . "&", true));
    $params["Signature"] = $sign;

    // 发起请求
    $url = "https://dysmsapi.aliyuncs.com/?" . http_build_query($params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);

    // 可选：记录日志或返回结果
    $result = json_decode($output, true);
    
    // var_dump($result);
    
    if (!isset($result['Code']) || $result['Code'] !== 'OK') {
        // 可记录失败日志
        \think\facade\Log::error('短信发送失败：' . json_encode($result));
    }
}

public function course()
{
    $name        = input('name', '');
    $category_id = input('category_id', '');
    $status      = input('status', ''); // 接收课程状态筛选

    $query = Db::name('sy_course')
        ->alias('c')
        ->join('sy_course_category cat', 'c.category_id = cat.id', 'LEFT')
        ->field('c.*, cat.name as category_name');

    if ($name !== '') {
        $query->where('c.name', 'like', "%{$name}%");
    }

    if ($category_id !== '') {
        $query->where('c.category_id', $category_id);
    }

    if ($status !== '') {
        $query->where('c.status', intval($status));
    }

    $courses = $query->order('c.id', 'desc')->select();
    $categories = Db::name('sy_course_category')->select();

    return $this->fetch('', [
        'courses'      => $courses,
        'categories'   => $categories,
        'name'         => $name,
        'category_id'  => $category_id,
        'status'       => $status // 传递状态给模板
    ]);
}

public function yyjl(){
    $records = Db::name('sy_course_booking')
        ->alias('b')
        ->join('sy_course c', 'b.course_id = c.id', 'LEFT')
        ->join('sy_user u', 'b.user_id = u.id', 'LEFT')
        ->field([
            'b.id',
            'b.user_id',
            'b.course_id',
            'b.create_time',
            'b.status',
            'c.name as course_name',
            'c.course_time',
            'u.name as user_name',
            'u.child_name',
            'u.phone',
        ])
        ->order('b.id', 'desc')
        ->select();

    foreach ($records as &$v) {
        $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        $v['course_time'] = $v['course_time'] ?: '未设置';
        $v['user_name'] = $v['user_name'] ?: '未填写';
        $v['child_name'] = $v['child_name'] ?: '未填写';
    }

    return $this->fetch('', [
        'records' => $records
    ]);
}

// 添加课程页面
public function course_add()
{
    $experts = Db::name('sy_expert')->field('id, name')->select();

    foreach ($experts as &$expert) {
        $expert['initial'] = $this->getFirstChar($expert['name']); // 调用拼音首字母方法
    }

    // 按拼音首字母排序
    usort($experts, function ($a, $b) {
        return strcmp($a['initial'], $b['initial']);
    });

    // 查询一级分类
    $categories = Db::name('sy_course_category')
                    ->where('level', 1)
                    ->select();

    // 查询对应的二级分类
    foreach ($categories as &$cat) {
        $cat['children'] = Db::name('sy_course_category')
                             ->where('pid', $cat['id'])
                             ->select();
    }

    // 课程模板
    $tplList = Db::name('sy_course_template')->order('id desc')->select();

    return $this->fetch('', [
        'expert_list'   => $experts,
        'category_list' => $categories,
        'template_list' => $tplList
    ]);
}



public function save_course()
{
    $name         = input('name');
    $expert_ids   = input('expert_ids/a');
    $course_time  = input('course_time');
    $desc         = input('desc');
    $category_id  = input('category_id');
    $location     = input('location');
    $max_number   = input('max_number');
    $title_image  = input('title_image');
    $poster_image = input('poster_image');
    $replay_video = input('video_url');

    if (!$name || empty($expert_ids) || !$course_time || !$category_id || !$location || !$max_number) {
        return json(['code' => 0, 'msg' => '请填写完整信息']);
    }

    // 防重复校验：当天是否有相同课程名
    $startOfDay = strtotime(date('Y-m-d', strtotime($course_time)));
    $endOfDay   = $startOfDay + 86400 - 1;

    $exists = Db::name('sy_course')
        ->where('name', $name)
        ->whereBetween('course_time', [$startOfDay, $endOfDay])
        ->find();

    if ($exists) {
        return json(['code' => 0, 'msg' => '当天已存在相同课程名称，不能重复添加']);
    }

    // 拼接专家信息
    $expert_id_str   = implode(',', $expert_ids);
    $expert_name_arr = Db::name('sy_expert')->whereIn('id', $expert_ids)->column('name');
    $expert_name_str = implode(',', $expert_name_arr);

    $data = [
        'name'         => $name,
        'expert_id'    => $expert_id_str,
        'expert_name'  => $expert_name_str,
        'course_time'  => $course_time,
        'desc'         => $desc,
        'category_id'  => $category_id,
        'location'     => $location,
        'max_number'   => $max_number,
        'title_image'  => $title_image,
        'poster_image' => $poster_image,
        'create_time'  => time(),
        'replay_video' => $replay_video,
    ];
    // var_dump($data);
    // die;
    $flag = Db::name('sy_course')->insertGetId($data);
    if (!$flag) {
        return json(['code' => 0, 'msg' => '操作失败']);
    }

    return json(['code' => 1, 'msg' => '操作成功']);
}

// 编辑课程页面
public function course_edit()
{
    $id = input('id');
    $record = Db::name('sy_course')->where('id', $id)->find();
    if (!$record) {
        $this->error('课程不存在');
    }
        $record['expert_ids'] = explode(',', $record['expert_id']);

    $expertList = Db::name('sy_expert')->field('id, name')->select();

    return $this->fetch('', [
        'record'      => $record,
        'expert_list' => $expertList
    ]);
}

public function getTemplateInfo()
{
    $id = input('id');
    $tpl = Db::name('sy_course_template')->where('id', $id)->find();

    if (!$tpl) {
        return json(['code' => 0, 'msg' => '模板不存在']);
    }

    // 兼容 PHP5.6 的写法
    $tpl['expert_ids'] = array_filter(explode(',', isset($tpl['expert_id']) ? $tpl['expert_id'] : ''));

    return json(['code' => 1, 'data' => $tpl]);
}



// 更新课程信息
public function edit_course()
{
    $id          = input('id');
    $name        = input('name');
    $expert_ids   = input('expert_ids/a'); 
    $course_time = input('course_time');
    $desc        = input('desc');
    $location    = input('location');
    $max_number  = input('max_number');
    $title_image  = input('title_image');
    $poster_image = input('poster_image');
     $replay_video = input('video_url');
    if (!$id || !$name || !$expert_ids || !$course_time || !$location || !$max_number) {
        return json(['code' => 0, 'msg' => '请填写完整信息']);
    }

    // $expert_name = Db::name('sy_expert')->where('id', $expert_id)->value('name');
      $expert_id_str   = implode(',', $expert_ids);
    $expert_name_arr = Db::name('sy_expert')->whereIn('id', $expert_ids)->column('name');
    $expert_name_str = implode(',', $expert_name_arr);
    $data = [
        'name'         => $name,
         'expert_id'    => $expert_id_str,
        'expert_name'  => $expert_name_str,
        'course_time'  => $course_time,
        'desc'         => $desc,
        'location'     => $location,
        'max_number'   => $max_number,
        'title_image'  => $title_image,
        'poster_image' => $poster_image,
         'replay_video' => $replay_video,
    ];

    $res = Db::name('sy_course')->where('id', $id)->update($data);
    if ($res === false) {
        return json(['code' => 0, 'msg' => '操作失败']);
    }

    return json(['code' => 1, 'msg' => '操作成功']);
}

// 删除课程
public function course_delete()
{
    $id = input('id');
    if (!$id) {
        return json(['code' => 0, 'msg' => '参数错误']);
    }

    Db::name('sy_course')->where('id', $id)->delete();

    return json(['code' => 1, 'msg' => '删除成功']);
}
 // 文章列表
public function article()
{
    $category = input('category/d', 0);
    $page = input('page/d', 1); // 当前页码
    $limit = 10; // 每页条数

    $articles = Db::name('sy_article')
        ->where('category', $category)
        ->order('id', 'desc')
        ->paginate($limit, false, [
            'page' => $page,
            'query' => ['category' => $category], // 保持分类切换
        ]);

    return $this->fetch('', [
        'articles' => $articles,
        'category' => $category
    ]);
}
// 添加文章页面
public function article_add()
{
    $category = input('category/d', 0); // 默认0
    return $this->fetch('', [
        'category' => $category
    ]);
}

// 保存文章（支持微信链接 & 正文）
public function save_article()
{
    $title = input('title');
    $type = input('type', 'content');
    $content = input('content', '');
    $link_url = input('link_url', '');
    $category = input('category/d', 0); 
    $desc = input('desc', '');
    if (!$title) return json(['code' => 0, 'msg' => '标题必填']);
    if ($type === 'link' && !$link_url) return json(['code' => 0, 'msg' => '微信文章链接必填']);
    if ($type === 'content' && !$content) return json(['code' => 0, 'msg' => '文章内容必填']);

    $data = [
        'title'        => $title,
        'type'         => $type,
        'link_url'     => $type === 'link' ? $link_url : '',
        'content'      => $type === 'content' ? $content : '',
        'category'     => $category,
        'desc'     => $desc,
        'create_time'  => time()
    ];

    $flag = Db::name('sy_article')->insertGetId($data);
    return $flag ? json(['code' => 1, 'msg' => '保存成功']) : json(['code' => 0, 'msg' => '保存失败']);
}


// 编辑文章页面
public function article_edit()
{
    $id = input('id');
    $record = Db::name('sy_article')->where('id', $id)->find();
    return $this->fetch('', [
        'record' => $record,
        'category' => isset($record['category']) ? $record['category'] : 0
    ]);
}

// 更新文章（支持类型变更）
public function edit_article()
{
    $id       = input('id');
    $title    = input('title');
    $type     = input('type', 'content'); // content 或 link
    $content  = input('content', '');
    $link_url = input('link_url', '');
    $desc     = input('desc');

    if (!$id || !$title) {
        return json(['code' => 0, 'msg' => '标题必填']);
    }

    // 类型校验
    if (!in_array($type, ['content', 'link'])) {
        return json(['code' => 0, 'msg' => '文章类型错误']);
    }

    // 内容校验
    if ($type === 'link' && !$link_url) {
        return json(['code' => 0, 'msg' => '微信文章链接必填']);
    }

    if ($type === 'content' && (!$content || trim(strip_tags($content)) === '')) {
        return json(['code' => 0, 'msg' => '文章内容必填']);
    }

    $data = [
        'title'    => $title,
        'type'     => $type,
        'desc'     => $desc,
        'link_url' => $type === 'link' ? $link_url : '',
        'content'  => $type === 'content' ? $content : ''
    ];

    $res = Db::name('sy_article')->where('id', $id)->update($data);

    if ($res !== false) {
        return json(['code' => 1, 'msg' => '更新成功']);
    } else {
        return json(['code' => 0, 'msg' => '更新失败']);
    }
}

// 删除文章
public function article_delete()
{
    $id = input('id');
    Db::name('sy_article')->where('id', $id)->delete();
    return json(['code' => 1, 'msg' => '删除成功']);
}

// 课程评价列表
public function pj()
{
    $list = Db::name('sy_course_rating')
        ->alias('r')
        ->join('sy_user u', 'r.user_id = u.id', 'left')
        ->join('sy_course c', 'r.course_id = c.id', 'left')
        ->field('r.id, u.nickname, c.name as course_name, r.content_rating, r.style_rating, r.comment, r.create_time')
        ->order('r.id desc')
        ->select();

    // 格式化时间
    foreach ($list as &$item) {
        $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
    }

    return $this->fetch('', [
        'ratings' => $list
    ]);
}

public function courseTemplate()
{
    $templates = Db::name('sy_course_template')->order('id desc')->select();

    foreach ($templates as &$v) {
        $v['category_name'] = Db::name('sy_course_category')->where('id', $v['category_id'])->value('name');
    }

    return $this->fetch('', [
        'templates' => $templates
    ]);
}




// 添加课程模板页面
public function course_template_add()
{
    $experts = Db::name('sy_expert')->field('id, name')->select();

    foreach ($experts as &$expert) {
        $expert['initial'] =  $this->getFirstChar($expert['name']);  // 调用上面的拼音函数
    }

    usort($experts, function ($a, $b) {
        return strcmp($a['initial'], $b['initial']);
    });

    $categories = Db::name('sy_course_category')->where('level', 1)->select();
    foreach ($categories as &$cat) {
        $cat['children'] = Db::name('sy_course_category')->where('pid', $cat['id'])->select();
    }

    return $this->fetch('', [
        'expert_list' => $experts,
        'category_list' => $categories
    ]);
}
function getFirstChar($str) {
    $firstChar = ord(substr($str, 0, 1));
    if ($firstChar >= 65 && $firstChar <= 90 || $firstChar >= 97 && $firstChar <= 122) {
        return strtoupper(substr($str, 0, 1)); // 英文直接返回大写首字母
    }

    // 中文拼音首字母区间匹配
    $fchar = ord($str[0]);
    if ($fchar >= 0 && $fchar < 160) return '#'; // 非中文或不可识别字符

    $s1 = iconv('UTF-8', 'gb2312//IGNORE', $str);
    $s2 = iconv('gb2312', 'UTF-8//IGNORE', $s1);
    $s = $s2 === $str ? $s1 : $str;

    $asc = ord($s[0]) * 256 + ord($s[1]) - 65536;

    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return '#';
}

public function save_course_template()
{
    $data = input();

    if (empty($data['name']) || empty($data['expert_ids']) || empty($data['category_id']) || empty($data['location'])) {
        return json(['code' => 0, 'msg' => '请填写完整信息']);
    }
        if (!isset($data['max_number']) || !is_numeric($data['max_number']) || intval($data['max_number']) <= 0) {
        return json(['code' => 0, 'msg' => '最大预约人数必须为正整数']);
    }


    // 处理专家 ID 和名字
    $expertIds = $data['expert_ids'];
    $expertIdStr = implode(',', $expertIds);
    $expertNames = Db::name('sy_expert')->whereIn('id', $expertIds)->column('name');
    $expertNameStr = implode('，', $expertNames);

    $insertData = [
        'name'         => $data['name'],
        'expert_id'   => $expertIdStr,
        'expert_name' => $expertNameStr,
        'category_id'  => $data['category_id'],
        'location'     => $data['location'],
        'max_number'   => $data['max_number'],
        'desc'         => $data['desc'],
        'title_image'  => $data['title_image'],
        'poster_image' => $data['poster_image'],
        'create_time'  => time()
    ];

    $res = Db::name('sy_course_template')->insertGetId($insertData);
    return $res
        ? json(['code' => 1, 'msg' => '模板添加成功'])
        : json(['code' => 0, 'msg' => '操作失败']);
}

public function course_template_edit()
{
    $id = input('id');
    $record = Db::name('sy_course_template')->where('id', $id)->find();
    if (!$record) {
        $this->error('模板不存在');
    }

    // ✅ 把 expert_id 字符串变成数组，方便模板中处理
    $record['expert_ids'] = explode(',', $record['expert_id']);

    $expertList = Db::name('sy_expert')->field('id, name')->select();
    $categories = Db::name('sy_course_category')->where('level', 1)->select();
    foreach ($categories as &$cat) {
        $cat['children'] = Db::name('sy_course_category')->where('pid', $cat['id'])->select();
    }

    return $this->fetch('', [
        'record' => $record,
        'expert_list' => $expertList,
        'category_list' => $categories
    ]);
}



public function edit_course_template()
{
    $id = input('id');
    $data = input();

    $expert_ids = input('expert_ids/a'); // 接收数组
    if (!$id || empty($data['name']) || empty($expert_ids) || empty($data['category_id']) || empty($data['location'])) {
        return json(['code' => 0, 'msg' => '请填写完整信息']);
    }

    $data['expert_id']   = implode(',', $expert_ids);
    $data['expert_name'] = implode(',', Db::name('sy_expert')->where('id', 'in', $expert_ids)->column('name'));

    $res = Db::name('sy_course_template')->where('id', $id)->update($data);
    if ($res !== false) {
        return json(['code' => 1, 'msg' => '模板更新成功']);
    } else {
        return json(['code' => 0, 'msg' => '操作失败']);
    }
}



public function course_template_delete()
{
    $id = input('id');
    if (!$id) {
        return json(['code' => 0, 'msg' => '参数错误']);
    }

    Db::name('sy_course_template')->where('id', $id)->delete();
    return json(['code' => 1, 'msg' => '删除成功']);
}


public function generate_course_from_template()
{
    $template_id = input('template_id');
    $template = Db::name('sy_course_template')->where('id', $template_id)->find();

    if (!$template) {
        return json(['code' => 0, 'msg' => '模板不存在']);
    }

    $template['create_time'] = time();
    unset($template['id']); // 移除模板id
    $res = Db::name('sy_course')->insert($template);

    if ($res) {
        return json(['code' => 1, 'msg' => '课程生成成功']);
    } else {
        return json(['code' => 0, 'msg' => '操作失败']);
    }
}


public function export_expert()
{
    // 引入 PHPExcel
    \think\Loader::import('classes.PHPExcel', EXTEND_PATH, '.php');
    \think\Loader::import('classes.PHPExcel.Writer.Excel5', EXTEND_PATH, '.php');

    // 查询专家数据
    $experts = Db::name('sy_expert')->order('id', 'desc')->select();

    // 创建 Excel 实例
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties()->setTitle("专家列表")->setDescription("专家导出");

    // 设置表头
    $sheet = $objPHPExcel->setActiveSheetIndex(0);
    $sheet->setTitle('专家列表');
    $sheet->setCellValue('A1', 'ID');
    $sheet->setCellValue('B1', '姓名');
    $sheet->setCellValue('C1', '简介');
    $sheet->setCellValue('D1', '图片地址');

    // 填充数据
    $rowIndex = 2;
    foreach ($experts as $exp) {
        $sheet->setCellValue("A{$rowIndex}", $exp['id']);
        $sheet->setCellValue("B{$rowIndex}", $exp['name']);
        $sheet->setCellValue("C{$rowIndex}", $exp['desc']);
        $sheet->setCellValue("D{$rowIndex}", request()->domain() . '/public/' . $exp['img']);
        $rowIndex++;
    }

    // 设置输出头
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="专家列表.xls"');
    header('Cache-Control: max-age=0');

    // 输出 Excel 文件
    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $writer->save('php://output');
    exit;
}


public function export_rating()
{
        \think\Loader::import('classes.PHPExcel', EXTEND_PATH, '.php');
    \think\Loader::import('classes.PHPExcel.Writer.Excel5', EXTEND_PATH, '.php');

    $data = Db::name('sy_course_rating')
        ->alias('r')
        ->join('sy_user u', 'r.user_id = u.id', 'left')
        ->join('sy_course c', 'r.course_id = c.id', 'left')
        ->field('r.id, u.nickname, c.name as course_name, r.content_rating, r.style_rating, r.comment, r.create_time')
        ->order('r.id desc')
        ->select();

    $objPHPExcel = new \PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();

    // 表头
    $headers = ['ID', '用户昵称', '课程名称', '内容评分', '语言评分', '评价内容', '评价时间'];
    $col = 'A';
    foreach ($headers as $header) {
        $sheet->setCellValue($col . '1', $header);
        $col++;
    }

    // 数据行
    $rowIndex = 2;
    foreach ($data as $row) {
        $sheet->setCellValue("A{$rowIndex}", $row['id']);
        $sheet->setCellValue("B{$rowIndex}", $row['nickname']);
        $sheet->setCellValue("C{$rowIndex}", $row['course_name']);
        $sheet->setCellValue("D{$rowIndex}", $row['content_rating']);
        $sheet->setCellValue("E{$rowIndex}", $row['style_rating']);
        $sheet->setCellValue("F{$rowIndex}", $row['comment']);
        $sheet->setCellValue("G{$rowIndex}", date('Y-m-d H:i:s', $row['create_time']));
        $rowIndex++;
    }

    // 输出 Excel 文件
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="课程评价导出.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $writer->save('php://output');
    exit;
}


public function export_course()
{
           \think\Loader::import('classes.PHPExcel', EXTEND_PATH, '.php');
    \think\Loader::import('classes.PHPExcel.Writer.Excel5', EXTEND_PATH, '.php');


    $name        = input('name', '');
    $category_id = input('category_id', '');
    $status      = input('status', '');

    $query = Db::name('sy_course')
        ->alias('c')
        ->join('sy_course_category cat', 'c.category_id = cat.id', 'LEFT')
        ->field('c.id, c.name, cat.name as category_name, c.expert_name, c.course_time, c.desc, c.max_number, c.booked, c.status');

    if ($name !== '') {
        $query->where('c.name', 'like', "%{$name}%");
    }

    if ($category_id !== '') {
        $query->where('c.category_id', $category_id);
    }

    if ($status !== '') {
        $query->where('c.status', intval($status));
    }

    $list = $query->order('c.id desc')->select();

    $objPHPExcel = new \PHPExcel();
    $sheet = $objPHPExcel->getActiveSheet();

    // 表头
    $headers = ['ID', '课程名', '分类', '专家', '上课时间', '介绍', '最大预约数', '已预约数', '状态'];
    $col = 'A';
    foreach ($headers as $header) {
        $sheet->setCellValue($col . '1', $header);
        $col++;
    }

    // 数据
    $rowIndex = 2;
    foreach ($list as $row) {
       $statusMap = ['未上课', '已上课', '已取消'];
      $statusText = isset($statusMap[$row['status']]) ? $statusMap[$row['status']] : '未知';

        $sheet->setCellValue("A{$rowIndex}", $row['id']);
        $sheet->setCellValue("B{$rowIndex}", $row['name']);
        $sheet->setCellValue("C{$rowIndex}", $row['category_name']);
        $sheet->setCellValue("D{$rowIndex}", $row['expert_name']);
        $courseTime = is_numeric($row['course_time']) 
            ? date('Y-m-d H:i:s', $row['course_time']) 
            : $row['course_time'];
        
        $sheet->setCellValue("E{$rowIndex}", $courseTime);
        $sheet->setCellValue("F{$rowIndex}", $row['desc']);
        $sheet->setCellValue("G{$rowIndex}", $row['max_number']);
        $sheet->setCellValue("H{$rowIndex}", $row['booked']);
        $sheet->setCellValue("I{$rowIndex}", $statusText);
        $rowIndex++;
    }

    // 下载文件
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="课程导出.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $writer->save('php://output');
    exit;
}


public function application()
{
    $name   = input('name', '');
    $type   = input('type', '');
    $status = input('status', '0'); // 默认查询待审核
    $page   = input('page', 1);
    $limit  = 10;

    $query = Db::name('sy_jzfw_applications')->alias('a');

    if ($name !== '') {
        $query->where('a.name', 'like', "%{$name}%");
    }

    if ($type !== '') {
        $query->where('a.type', $type);
    }

    if ($status !== '') {
        $query->where('a.status', intval($status));
    }

    // 获取分页对象
    $applications = $query
        ->order('a.id', 'desc')
        ->paginate([
            'list_rows' => $limit,
            'page'      => $page,
            'query'     => request()->param(),
        ]);

    // 获取分页数据项（数组形式）
    $list = $applications->items();
// var_dump($list);
    // 解密身份证字段
    foreach ($list as &$item) {
       $item['id_card'] = $this->aesDecrypt(isset($item['id_card']) ? $item['id_card'] : '');
       $item['child_id_card'] = $this->aesDecrypt(isset($item['child_id_card']) ? $item['child_id_card'] : '');
       $item['jiedao'] =  $query = Db::name('sy_district')->where('id', $item['district_id'])->value('name');
       $pid =  $query = Db::name('sy_district')->where('id', $item['district_id'])->value('pid');
       $item['shequ']  =  $query = Db::name('sy_district')->where('id', $pid)->value('name');
       if($item['application_time']){
          $item['application_time']  = date('Y-m-d H:i:s',$item['application_time']); 
       }
       if($item['create_time']){
          $item['create_time']  = date('Y-m-d H:i:s',$item['create_time']); 
       }

    }
    
    // die;
    return $this->fetch('', [
        'applications' => $applications, // 原分页对象，用于渲染分页条
        'list'         => $list,         // 解密后的数据列表
        'name'         => $name,
        'type'         => $type,
        'status'       => $status,
    ]);
}


public function fw_list()
{
    $name   = input('name', '');
    $page   = input('page', 1);
    $limit  = 10;
    $query = Db::name('sy_jzfw_feedback')
        ->alias('f')
        ->join('sy_jzfw_applications a', 'f.reg_id = a.id', 'LEFT')
        ->field('f.*, a.name');

    if ($name !== '') {
        $query->where('a.name', 'like', "%{$name}%");
    }

    $feedbacks = $query
        ->order('f.id desc')
        ->paginate([
            'list_rows' => $limit,
            'page'      => $page,
            'query'     => request()->param(),
        ]);

    $list = $feedbacks->items();
    // 格式化时间和状态
    foreach ($list as &$item) {
        $item['assign_time'] = date('Y-m-d H:i:s', strtotime($item['assign_time']));
        $item['server_start_time'] = date('Y-m-d H:i:s', strtotime($item['server_start_time']));
        $item['server_end_time'] = date('Y-m-d H:i:s', strtotime($item['server_end_time']));
        $item['status_text'] = $item['is_cancel'] ? '已取消' : '已服务';
    }

    return $this->fetch('', [
        'feedbacks' => $feedbacks,
        'list'      => $list,
        'name'      => $name,
    ]);
}


protected function aesDecrypt($encrypted)
{
    $key = '1234567890abcdef'; // 前后端 AES 密钥一致
    return openssl_decrypt(base64_decode($encrypted), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
}
public function approve_application()
{
    $id = input('id');

    $applicationData = Db::name('sy_jzfw_applications')->where('id', $id)->find();
    if (!$applicationData) {
        return json(['code' => 0, 'msg' => '申请记录不存在']);
    }

    // 解密字段
    $applicationData['id_card'] = $this->aesDecrypt($applicationData['id_card']);
    $applicationData['child_id_card'] = $this->aesDecrypt($applicationData['child_id_card']);
    $applicationData['phone'] = $applicationData['phone'];
    $applicationData['address'] = $applicationData['address'];
    $applicationData['note'] = $applicationData['note'];

    // 获取 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);

    if (empty($tokenData['access_token'])) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 组装同步参数（使用解密后的字段）
    $syncUrl = 'http://180.101.176.137:13306/sdcc/tyy/syncServerObject';
    $syncHeaders = [
        'Blade-Auth: ' . $tokenData['access_token'],
    ];
    $areaId = Db::name('sy_district')->where('id', $applicationData['district_id'])->value('pid');
    $syncQueryData = http_build_query([
        'id'             => $applicationData['id'],
        'name'           => $applicationData['name'],
        'id_card'        => $applicationData['id_card'],
        'phone'          => $applicationData['phone'],
        'address'        => $applicationData['address'],
        'child_name'     => $applicationData['child_name'],
        'child_id_card'  => $applicationData['child_id_card'],
        'areaId'         => $areaId,
        'stationId'      => $applicationData['district_id'],
    ]);
    // var_dump($syncQueryData);
    // die;
    $syncResponse = $this->httpRequest($syncUrl . '?' . $syncQueryData, '', $syncHeaders, 'GET');
    $syncData = json_decode($syncResponse, true);

    // 记录日志
    $this->logSyncRequest(
        $applicationData['id'],
        $syncUrl . '?' . $syncQueryData,
        'GET',
        $syncHeaders,
        $syncQueryData,
        $syncResponse
    );

    // 判断是否同步成功
    if (!isset($syncData['code']) || $syncData['code'] != 200 || !$syncData['success']) {
        $msg = isset($syncData['msg']) ? $syncData['msg'] : '同步失败';
        return json(['code' => 0, 'msg' => $msg]);
    }

    // 同步成功后再更新状态
    
    $admin_id =  Session::get('admin_id');
    $admin_user = Db::name('admin_user')->field('id,username,name,img')->where('id', $admin_id)->find();

    $res = Db::name('sy_jzfw_applications')->where('id', $id)->update([
        'status' => 1,
        // 'yl_id'  => $syncData['data'],
        // 'yl_id'  => $syncData['data'],
        'admin_id'  => $admin_user['id'],
        'admin_name'  => $admin_user['name'],
        'application_time'=>time()

    ]);

    if (!$res) {
        return json(['code' => 0, 'msg' => '同步成功，但状态更新失败']);
    }

    $msg = isset($syncData['msg']) ? $syncData['msg'] : '审核并同步成功';
    return json(['code' => 1, 'msg' => $msg]);
}


public function get_service_type_list()
{
    
    // var_dump(222);
    // die;
    // 获取 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);
    // var_dump($tokenData);
    // die;
    if (empty($tokenData['access_token'])) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 请求服务大类接口
    $serviceUrl = 'http://180.101.176.137:13306/sdcc/tyy/queryServiceTypeList';
    $serviceHeaders = [
        'Blade-Auth: ' . $tokenData['access_token'],
    ];
    // var_dump($tokenData['access_token']);
    // die;
    $serviceResponse = $this->httpRequest($serviceUrl, '', $serviceHeaders, 'GET');
    $serviceData = json_decode($serviceResponse, true);
    // var_dump($serviceData);
    // die;
    // 判断返回结果
    if (!isset($serviceData['code']) || $serviceData['code'] != 200 || !$serviceData['success']) {
        $msg = isset($serviceData['msg']) ? $serviceData['msg'] : '获取失败';
        return json(['code' => 0, 'msg' => $msg]);
    }

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $serviceData['data'],
    ]);
}

public function get_service_subtype_list()
{
    $parentId = 126; // 大类 ID
    if (!$parentId) {
        return json(['code' => 0, 'msg' => '缺少大类 ID']);
    }

    // 获取 token
    $tokenUrl = 'http://180.101.176.137:13306/blade-auth/oauth/token';
    $tokenHeaders = [
        'Authorization: Basic c2FiZXI6c2FiZXJfc2VjcmV0',
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $tokenPostData = http_build_query([
        'grant_type' => 'password',
        'username'   => 'yedj',
        'password'   => '9aa253d2c57f0130d0552df3ccdec34c',
    ]);
    $tokenResponse = $this->httpRequest($tokenUrl, $tokenPostData, $tokenHeaders);
    $tokenData = json_decode($tokenResponse, true);

    if (empty($tokenData['access_token'])) {
        return json(['code' => 0, 'msg' => 'Token获取失败']);
    }

    // 请求服务子类接口
    $subtypeUrl = 'http://180.101.176.137:13306/sdcc/tyy/queryServiceSubTypeList';
    $subtypeHeaders = [
        'Blade-Auth: ' . $tokenData['access_token'],
        'Content-Type: application/json',
    ];
    $postData = json_encode(['parentId' => $parentId]);

    $subtypeResponse = $this->httpRequest($subtypeUrl, $postData, $subtypeHeaders, 'POST');
    $subtypeData = json_decode($subtypeResponse, true);

    if (!isset($subtypeData['code']) || $subtypeData['code'] != 200 || !$subtypeData['success']) {
        $msg = isset($subtypeData['msg']) ? $subtypeData['msg'] : '获取失败';
        return json(['code' => 0, 'msg' => $msg]);
    }

    return json([
        'code' => 1,
        'msg' => '获取成功',
        'data' => $subtypeData['data'],
    ]);
}
protected function logSyncRequest($applicationId, $url, $method, $headers, $query, $response)
{
    $decoded = json_decode($response, true);
    Db::name('sy_jzfw_sync_log')->insert([
        'application_id'   => $applicationId,
        'request_url'      => $url,
        'request_method'   => $method,
        'request_headers'  => json_encode($headers, JSON_UNESCAPED_UNICODE),
        'request_query'    => $query,
         'response_code' => isset($syncData['code']) ? $syncData['code'] : null,
        'response_msg'  => isset($syncData['msg']) ? $syncData['msg'] : '无返回信息',
        'response_data'    => $response,
        'create_time'      => time()
    ]);
}
public function reject_application()
{
    $id = input('post.id');
    $reasonType = input('post.reason_type');
    $reason = input('post.reason');

    $res = Db::name('sy_jzfw_applications')->where('id', $id)->update([
        'status'       => 2,
        'reason_type'  => $reasonType,
        'reason'       => $reason
    ]);

    return json(['code' => $res ? 1 : 0, 'msg' => $res ? '已拒绝审核' : '操作失败']);
}
public function discard_application()
{
    $id = input('post.id');
    $reason_type = input('post.reason_type', '');
    $reason = input('post.reason', '');

    $application = Db::name('sy_jzfw_applications')->find($id);
    if (!$application) {
        return json(['code' => 0, 'msg' => '记录不存在']);
    }

    // 判断是否已经废单过
    $exists = Db::name('sy_jzfw_discard')->where('application_id', $application['id'])->find();
    if ($exists) {
        return json(['code' => 0, 'msg' => '该记录已被废单，不能重复操作']);
    }

    Db::startTrans();
    try {
        // 写入废单记录
        Db::name('sy_jzfw_discard')->insert([
            'application_id' => $application['id'],
            'user_id'        => $application['user_id'],
            'create_time'    => time(),
            'reason'         => $reason_type . '；' . $reason
        ]);

        // 同步更新主表状态为已拒绝，并保存理由
        Db::name('sy_jzfw_applications')->where('id', $id)->update([
            'status'       => 2,
            'reason_type'  => $reason_type,
            'reason'       => $reason
        ]);

        Db::commit();
        return json(['code' => 1, 'msg' => '已废单并标记为拒绝']);
    } catch (\Exception $e) {
        Db::rollback();
        return json(['code' => 0, 'msg' => '废单失败：' . $e->getMessage()]);
    }
}

public function reset_application()
{
    $id = input('post.id');
    $res = Db::name('sy_jzfw_applications')->where('id', $id)->update(['status' => 0]);
    return json(['code' => $res ? 1 : 0, 'msg' => $res ? '状态已重置为待审核' : '重置失败']);
}
private function httpRequest($url, $data = null, $headers = [], $method = 'POST')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    }

    if (strtoupper($method) === 'GET') {
        curl_setopt($ch, CURLOPT_HTTPGET, true);
    }

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
public function discard_list()
{
    $name = input('name', '');

    $query = Db::name('sy_jzfw_discard')
        ->alias('d')
        ->join('sy_jzfw_applications a', 'd.application_id = a.id', 'LEFT')
        ->field('d.*, a.name, a.phone, a.type, a.end_time, a.create_name');

    if ($name !== '') {
        $query->where('a.name', 'like', "%{$name}%");
    }

    $list = $query->order('d.id desc')->select();

    return $this->fetch('', [
        'list' => $list,
        'name' => $name
    ]);
}

}
